import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
// import 'package:cached_network_image/cached_network_image.dart';
import 'dart:io';

void main() => runApp(MyImagePicker());

class MyImagePicker extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ImagePicker',
      theme: ThemeData.dark(),
      debugShowCheckedModeBanner: false,
      home: ImagePickWidget(),
    );
  }
}

class ImagePickWidget extends StatefulWidget {
  @override
  _ImagePickWidgetState createState() => _ImagePickWidgetState();
}

class _ImagePickWidgetState extends State<ImagePickWidget> {
  List imageList = new List<File>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ImagePicker'),
      ),
      body: _getbody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (imageList.length == 9) {
            showDialog<Null>(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: new Text('提示'),
                  content: SingleChildScrollView(
                    child: ListBody(
                      children: <Widget>[Text('最多只能添加9张图片')],
                    ),
                  ),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text('确定'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                );
              },
            );
          } else {
            _getImage();
          }
        },
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }

  //相册
  _getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    print(image);
    setState(() {
      if (image != null) {
        imageList.add(image);
      }
    });
  }

  _getbody() {
    if (showLoadingDialog()) {
      return getProgressDialog();
    } else {
      return getListView();
    }
  }

  bool showLoadingDialog() {
    if (imageList.length == 0) {
      return true;
    } else {
      return false;
    }
  }

  Center getProgressDialog() {
    return new Center(child: new CircularProgressIndicator());
  }

  getListView() {
    return Container(
      child: GridView.count(
          crossAxisCount: 3,
          padding: const EdgeInsets.all(10.0),
          mainAxisSpacing: 10.0,
          crossAxisSpacing: 10.0,
          children: List.generate(
              imageList.length,
              (index) => GestureDetector(
                    child: Center(
                      child: Padding(
                          padding: const EdgeInsets.all(1.0),
                          child: Image.file(
                            imageList[index],
                            height: 300.0,
                            width: 300.0,
                            fit: BoxFit.cover,
                            scale: 1.0,
                          )),
                    ),
                    onTap: () {
                      Navigator.of(context).push(
                        NinePicture(imageList, index),
                      );
                      print(imageList[index]);
                    },
                  ))),
    );
  }
  //   return GridView.builder(
  //     padding: const EdgeInsets.all(10.0),
  //     gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  //       crossAxisCount: 3,
  //       mainAxisSpacing: 10.0,
  //       crossAxisSpacing: 10.0,
  //     ),

  //     itemCount: imageList.length,
  //     itemBuilder: (BuildContext context, int index) {
  //       return Image.file(
  //         imageList[index],
  //         height: 300,
  //         fit: BoxFit.cover,
  //         scale: 1.0,
  //       );
  //     }
  //   );
  // }

}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            //  print()
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: Image.file(
                  widget.picList[index],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }
  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
